<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="businessId">
              <el-select v-model="filters.businessId" clearable filterable placeholder="商户">
                <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="waiterType">
              <el-select v-model="filters.waiterType" clearable placeholder="服务员类型">
                <el-option v-for="item in waiterTypeList" :key="item.value" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="userName">
              <el-input v-model="filters.userName" clearable placeholder="账号"></el-input>
            </el-form-item>
            <!-- <el-form-item prop="userCode">
              <el-input v-model="filters.userCode" clearable placeholder="编号"></el-input>
            </el-form-item> -->
            <el-form-item prop="nickName">
              <el-input v-model="filters.nickName" clearable placeholder="昵称"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="filters.phone" clearable placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="success" plain icon="fa fa-plus" v-has="permissionShift" @click="handleImportSchedule" size="mini">导入排班表</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table :data="dataList" @selection-change="handleSelection" :fit="true" highlight-current-row v-loading="listLoading" element-loading-text="数据加载中，请稍后..." empty-text="对不起，没有找到相关数据！">
        <!-- <el-table-column align="center" type="selection" width="100"></el-table-column> -->
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="scope.row.waiterType == 1 ? '' : 'success'">
                {{ scope.row.waiterType == 1 ? '专属' : '公共' }}
              </el-tag>
            </span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="工作类型">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="scope.row.jobType == 1 ? 'success' : 'info'">
                {{ scope.row.jobType == 1 ? '时段产品专员' : '普通' }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="编号" prop="userCode"></el-table-column> -->
        <el-table-column align="center" label="账号" prop="userName"></el-table-column>
        <el-table-column align="center" label="昵称" prop="nickName"></el-table-column>
        <el-table-column align="center" label="真实姓名" prop="fullName"></el-table-column>
        <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <div>
              {{ scope.row.sex == 1 ? '男' : '女' }}
            </div>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label="年龄" prop="age"></el-table-column>-->
        <el-table-column align="center" label="联系电话" prop="phone"></el-table-column>
        <el-table-column align="center" label="所属商户">
          <template slot-scope="scope">
            <div>
              {{ getBusinessName(scope.row.businessId) }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="接单方式">
          <template slot-scope="{row}">
            <div>
              {{ row.takeOrdersWay==1?'手动接单':'自动接单' }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column align="center" width="200" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                <!-- <el-dropdown-item v-has="permissionShift" @click.native="handleImportSchedule(scope.row)">
                        导入排班
                  </el-dropdown-item> -->
                <el-dropdown-item v-has="permissionShift" @click.native="handleCheckShift(scope.row)"> 查看排班 </el-dropdown-item>
                <el-dropdown-item v-has="permissionAccount" @click.native="handleClickAccount(scope.row)">资质账户</el-dropdown-item>
                <el-dropdown-item v-has="permissionSetAddress" @click.native="handleSetAddress(scope.row)">设置管理范围 </el-dropdown-item>
                <el-dropdown-item v-has="permissionCashSet" @click.native="handleCashSet(scope.row)">提现设置</el-dropdown-item>
                <el-dropdown-item v-has="permissionSetDepart" @click.native="handleSetDepart(scope.row)">设置部门</el-dropdown-item>
                <el-dropdown-item v-has="permissionOpenNotify" v-if="scope.row.openState == 0" @click.native="handleClickOpenNotify(scope.row)">开通服务通知</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <!-- 设置部门 -->
    <el-dialog center :visible.sync="setDepart.showSetDepart" title="设置部门" width="400px">
      <div>
        <el-cascader style="width: 100%" placeholder="请选择部门" v-model="setDepart.departIds" :props="{ label: 'departName', value: 'departId', checkStrictly: true }" :options="setDepart.departList"> </el-cascader>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="confirmSetDepart"> 确认 </el-button>
        <el-button @click="setDepart.showSetDepart = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 查看班次 -->
    <el-dialog center :visible.sync="shift.show" title="排班表" width="fit-content">
      <el-table :data="shift.list" max-height="500px" :span-method="handleMerge" border>
        <el-table-column label="日期" prop="workDate" align="center" width="200"></el-table-column>
        <el-table-column label="班次名称" prop="shiftName" align="center" width="130"></el-table-column>
        <el-table-column label="开始时间" prop="startTime" align="center" width="200"></el-table-column>
        <el-table-column label="结束时间" prop="endTime" align="center" width="200"></el-table-column>
      </el-table>
    </el-dialog>
    <!-- 提现设置 -->
    <CashSet :show.sync="cashSet.show" :info="cashSet.info" @confirm="confirmCashSet"></CashSet>

    <!-- 设置管理范围 -->
    <SetAddress :show.sync="setAddress.show" :list="setAddress.list" @confirm="confirmSetAddress" :level="setAddress.level"></SetAddress>

    <!-- 社区商户设置管理范围 -->
    <el-dialog :visible.sync="setAddress.show2" title="设置管理范围" width="fit-content" center :close-on-click-modal="false">
      <el-table ref="addressRef" :data="setAddress.allList" @row-click="$refs.addressRef.toggleRowSelection($event)" @selection-change="setAddress.list = $event">
        <el-table-column type="selection" align="center" width="100"></el-table-column>
        <el-table-column label="地区" align="center" width="340">
          <template slot-scope="{ row }">
            {{ formatAddress(row) }}
          </template>
        </el-table-column>
        <el-table-column label="小区" prop="villageName" align="center" width="220"></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmSetAddress">确定</el-button>
        <el-button @click="setAddress.show2 = false">取消</el-button>
      </div>
    </el-dialog>

    <UploadFile ref="uploadFileRef" accept="excel" @uploadFileList="getFileList"></UploadFile>
  </div>
</template>
<script>
import CashSet from '../../components/CashSet.vue';
import UploadFile from '../../components/UploadFile.vue';
import BusinessApi from '@/api/business/business';
import WaiterApi from '@/api/business/waiter';
import BusinessDepartApi from '@/api/business/depart';
import SetAddress from '@/components/SetAddress.vue';
import AdminVillageApi from '@/api/common/adminVillage';
import AccountInfoApi from '@/api/account/accountInfo';
import * as message from '@/constants/message';
import { getStorage } from '@/utils/auth';
import { USER_INFO } from '@/constants/storeName';
export default {
  name: 'WaiterManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      listLoading: true,
      filters: {
        nickName: '',
        // userCode: "",
        businessId: '',
        waiterType: '',
        phone: '',
        userName: '',
        businessId: '',
      },
      //服务员类别(1.商户服务员 2:公共服务员)
      waiterTypeList: [
        { value: 1, label: '专属服务员' },
        { value: 2, label: '公共服务员' },
      ],
      businessList: [],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },

      permissionAdd: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_DELETE',
      permissionOpenNotify: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_OPEN_NOTIFY',
      permissionSetDepart: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_SET_DEPART',
      permissionCashSet: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_CASHSET',
      permissionSetAddress: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_SET_ADDRESS',
      permissionAccount: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_ACCOUNT',
      permissionShift: 'SYSTEM_MANAGER_BUSINESS_WAITER_LIST_SHIFT',
      setDepart: {
        showSetDepart: false,
        waiterId: '',
        departList: [],
        departIds: [],
      },
      shift: {
        show: false,
        list: [],
      },
      cashSet: {
        show: false,
        info: {
          cashType: '',
          settleType: '',
          settleDay: '',
          cashDay: 1,
          userType: 3,
        },
      },
      rowItem: null,
      setAddress: {
        show: false,
        show2: false, // 社区商户弹框显示
        allList: [], // 社区商户的时候获取全部可选的列表
        list: [], // 社区商户服务员的过滤选中的list
        level: 5,
      },
    };
  },
  components: {
    CashSet,
    SetAddress,
    UploadFile,
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  watch: {
    //to去哪，from从哪来
    // $route(to,from){
    //   if(from.path =='/equip/specimenEdit' || from.path=='/equip/specimenAdd'){
    //       this.listData();
    //   }
    // }
  },
  methods: {
    init() {
      let _this = this;
      // 获取用户的角色信息
      _this.listLoading = true;
      _this.listData();
      _this.getBusinessList();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    handleSelection(list) {
      this.selectedRows = list;
    },
    // 合并日期相同的
    handleMerge({ row, column, rowIndex, columnIndex }) {
      if (columnIndex !== 0) return;
      const { list } = this.shift;
      const idx = list.findIndex((item) => item.workDate == row.workDate);
      if (rowIndex == idx) {
        const num = list.filter((item) => item.workDate == row.workDate).length || 1;
        return [num, 1];
      } else {
        return [0, 0];
      }
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo({}).then((res) => {
        this.businessList = res.data;
      });
    },
    // 通过商户列id获取商户名称
    getBusinessName(id) {
      let value = this.businessList.find((item) => item.id == id);
      if (value) {
        return value.name;
      }
    },
    formatAddress(row) {
      let address = row.provinceName;
      row.cityName && (address = address + row.cityName);
      row.areaName && (address = address + row.areaName);
      row.streetName && (address = address + row.streetName);
      return address;
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/business/waiterAdd');
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/waiterEdit',
        query: { id: row.waiterId },
      });
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/waiterDetail',
        query: { id: row.waiterId },
      });
    },
    handleImportSchedule() {
      this.$refs.uploadFileRef.handleCreate();
    },
    // 获取文件列表
    async getFileList(val) {
      await WaiterApi.importScheduleInfo({ uploadUrl: val[0] });
      this.listData();
      this.$Utils.notifySuccess('导入成功');
    },
    async handleCheckShift(row) {
      const { data } = await WaiterApi.getScheduleList({ waiterId: row.waiterId });
      const { shift } = this;
      shift.show = true;
      shift.list = (data || []).map((item) => item.list.map((item2) => ({ ...item, ...item2 }))).flat();
      shift.list.forEach((item) => {
        item.workDate = item.workDate.split(' ')[0];
        item.startTime = item.startTime.split(' ')[1].split(':').slice(0, 2).join(':');
        item.endTime = item.endTime.split(' ')[1].split(':').slice(0, 2).join(':');
      });
    },
    handleClickAccount(row) {
      this.$router.push({
        path: '/business/qualityAccount',
        query: {
          id: row.userId,
        },
      });
    },
    handleClickOpenNotify(row) {
      let _this = this;
      let currentState = row.openState == 0 ? 1 : 2;
      this.$confirm(currentState ? '是否开通服务通知？' : '是否关闭服务通知', message.TITLE_PROMPT, {}).then(() => {
        WaiterApi.openWaiter({
          id: row.waiterId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },

    //设置部门
    handleSetDepart(row) {
      console.log(this.setDepart);
      this.setDepart.showSetDepart = true;
      this.setDepart.waiterId = row.waiterId;
      this.setDepart.departIds = [];
      this.getDepartList(row.businessId);
    },
    // 获取部门列表
    getDepartList(businessId) {
      BusinessDepartApi.listMangerTree({ businessId }).then((res) => {
        this.setDisabled(res.data);
        this.setDepart.departList = res.data || [];
        this.getRelationDepart();
      });
    },
    // 获取服务员关联的部门
    getRelationDepart() {
      WaiterApi.getRelationDepart({ waiterId: this.setDepart.waiterId }).then((res) => {
        const { departId, firstDepartId, secondDepartId, thirdDepartId } = res.data;
        const departIds = [];
        departId ? departIds.push(departId) : '';
        firstDepartId ? departIds.push(firstDepartId) : '';
        secondDepartId ? departIds.push(secondDepartId) : '';
        thirdDepartId ? departIds.push(thirdDepartId) : '';
        this.setDepart.departIds = departIds;
        // console.log(this.setDepart.departIds,295)
      });
    },
    // 确认设置部门
    confirmSetDepart() {
      if (this.setDepart.departIds.length == 0) {
        this.$message.error('请选择一个部门');
        return;
      }

      const departIds = this.setDepart.departIds;
      const params = {
        id: this.setDepart.waiterId,
        departId: departIds[0] || '',
        firstDepartId: departIds[1] || '',
        secondDepartId: departIds[2] || '',
        thirdDepartId: departIds[3] || '',
      };
      WaiterApi.setDepart(params).then((res) => {
        this.$Utils.notifySuccess('设置成功');
        this.setDepart.showSetDepart = false;
      });
    },
    setDisabled(list) {
      list.forEach((item) => {
        if (!item.power) {
          item.disabled = true;
        }
        if (item.children) {
          this.setDisabled(item.children);
        }
      });
    },
    // 设置管理范围
    async handleSetAddress(row) {
      const { setAddress } = this;
      const { waiterId, waiterType } = (this.rowItem = row);
      let res = await AdminVillageApi.listVillage({ waiterId });
      if (waiterType == 2) {
        setAddress.list = res.data || [];
        setAddress.show = true;
      } else {
        let res2 = await WaiterApi.checkoutWaterBusiness({ waiterId });
        // if(!res2.data) return
        setAddress.show2 = true;
        setAddress.allList = res2.data || [];
        await this.$nextTick();
        setAddress.allList.forEach((item) => {
          if (res.data.some((item2) => this.$Utils.isAddressSame(item, item2))) this.$refs.addressRef.toggleRowSelection(item);
        });
      }
      // const [res1,res2] = await Promise.all([await WaiterApi.checkoutWaterBusiness({waiterId}),await AdminVillageApi.listVillage({ waiterId })])
      // if(res1.data){
      //   setAddress.show2 = true
      //   setAddress.allList = res1.data||[]
      //   await this.$nextTick()
      //   setAddress.allList.forEach(item=>{
      //     if(res2.data.some(item2=>this.$Utils.isAddressSame(item,item2))) this.$refs.addressRef.toggleRowSelection(item)
      //   })
      // }else{
      //   setAddress.list = res2.data||[]
      //   setAddress.show = true
      // }
    },
    // 确认设置管理范围
    async confirmSetAddress() {
      const {
        rowItem: { waiterId },
        setAddress,
      } = this;
      const params = {
        waiterId,
        list: [],
      };
      await this.$confirm('确认保存', '提示', {});
      setAddress.list.forEach((item) => {
        const obj = { ...item };
        delete obj.adminVillageId;
        delete obj.villageList;
        params.list.push(Object.assign(obj, { levels: obj.villageId ? 5 : obj.levels }));
      });
      setAddress.show = false;
      setAddress.show2 = false;
      await AdminVillageApi.setManagementScope(params);
      this.$Utils.notifySuccess('设置成功');
    },
    // 提现设置
    async handleCashSet(row) {
      const { cashSet } = this;
      this.rowItem = row;
      const res = await AccountInfoApi.getAccountInfo({ userId: row.userId });
      if (res.data) {
        cashSet.info = res.data;
      } else {
        this.cashSet.info = this.$options.data().cashSet.info;
      }
      cashSet.show = true;
    },
    // 确认提现设置
    async confirmCashSet(val) {
      const {
        rowItem: { userId },
        cashSet,
      } = this;
      const params = {
        ...cashSet.info,
        userId,
      };
      cashSet.show = false;
      await AccountInfoApi.setAccountBase(params);
      this.$Utils.notifySuccess('设置成功');
    },
    handleIsDisable(row) {
      let _this = this;
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        WaiterApi.deleteWaiter({
          id: row.waiterId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        WaiterApi.deleteWaiter({
          id: val.waiterId,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      // 获取列表数据
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.nickName = _this.filters.nickName;
      // cond.userCode = _this.filters.userCode
      cond.businessId = _this.filters.businessId;
      cond.phone = _this.filters.phone;
      cond.waiterType = _this.filters.waiterType;
      cond.userName = _this.filters.userName;
      WaiterApi.listWaiter(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.listLoading = false;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
